import _ from 'lodash'
import { Setting } from '../models'

exports.setKey = async function(keyPath, value) {
  let key = keyPath

  let keys = key.split('.')
  let name = keys[0]

  let kv = await Setting.findOne({
    where: { key: name }
  })

  if (!kv) {
    let obj = {}
    _.set(obj, key, value)
    await Setting.create({
      key: name,
      value: JSON.stringify(obj)
    })
  } else {
    let obj = JSON.parse(kv.value)
    _.set(obj, key, value)
    await Setting.update(
      {
        value: JSON.stringify(obj)
      },
      {
        where: {
          key: name
        }
      }
    )
  }

  return true
}

exports.getKey = async function(keyPath, defaultValue = null) {
  let key = keyPath
  let keys = key.split('.')
  let name = keys[0]

  let kv = await Setting.findOne({
    where: { key: name }
  })
  if (!kv) {
    return defaultValue
  }
  let value = _.get(JSON.parse(kv.value), key, defaultValue)
  return value
}
